package com.baijia.web.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by dudu on 2016/10/25.
 */
public class Corsfilter extends OncePerRequestFilter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws ServletException, IOException {
        String path = request.getHeader("Origin");
        logger.info("[Corsfilter], path: " + path);
        if (path != null) {
            if (path.matches("^http(s)?://(.+\\.)?(baijiahulian\\.com)$")) {
                response.addHeader("Access-Control-Allow-Origin", path);
                response.addHeader("Access-Control-Allow-Credentials", "true");
            } else if (path.matches("^http(s)?://(.+\\.)?(genshuixue\\.com)$")) {
                response.addHeader("Access-Control-Allow-Origin", path);
                response.addHeader("Access-Control-Allow-Credentials", "true");
            }

            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type");
            response.addHeader("Access-Control-Max-Age", "3600");
        }
        filterChain.doFilter(request, response);

    }

}
